package com.gxa.modules.app.login.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.gxa.modules.app.login.common.AesCbcUtil;
import com.gxa.modules.app.login.common.RedisKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Random;

@Slf4j
@Component
public class WxService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    public String wxDecrypt(String encryptedData, String sessionId, String vi) throws Exception {


        // 开始解密
        String json =  redisTemplate.opsForValue().get(RedisKey.WX_SESSION_ID + sessionId);
        log.info("信息："+json);
        JSONObject jsonObject = JSON.parseObject(json);
        log.info("jsonObject信息："+jsonObject);
        String sessionKey = (String) jsonObject.get("session_key");

        System.out.println("-------------sessionkey===>" + sessionKey);
        System.out.println("-------------encryptedData===>" + encryptedData);
        System.out.println("-------------iv===>" + vi);
        String decrypt = AesCbcUtil.decrypt(encryptedData, sessionKey, vi, "UTF-8");

        System.out.println("-------------decrypt===>" + decrypt);

//        byte[] encData = cn.hutool.core.codec.Base64.decode(encryptedData);
//        byte[] iv = cn.hutool.core.codec.Base64.decode(vi);
//        byte[] key = Base64.decode(sessionKey);
        log.info("sessionKey:{}",sessionKey);
//        AlgorithmParameterSpec ivSpec = new IvParameterSpec(iv);
//        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
//        SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
//        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
//        return new String(cipher.doFinal(encData), "UTF-8");  //因为原本他应该返回字节数组的，你给Base64编码了，所以解密的时候先解码
        return decrypt;
    }

    //生成随机用户名，数字和字母组成,
    public String getStringRandom(int length) {

        StringBuilder val = new StringBuilder();
        Random random = new Random();

        //参数length，表示生成几位随机数
        for (int i = 0; i < length; i++) {

            String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
            //输出字母还是数字
            if ("char".equalsIgnoreCase(charOrNum)) {
                //输出是大写字母还是小写字母
                int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;
                val.append((char) (random.nextInt(26) + temp));
            } else {
                val.append(random.nextInt(10));
            }
        }
        return val.toString();
    }
}
